package com.models;

import java.util.List;
import net.sf.json.JSONObject;
import com.om.base.Many2one;
import com.om.base.One2many;
import com.om.base.PrimaryKey;
import com.om.base.Entity;
import com.om.base.Utils;
import com.om.common.BaseBean;

@Entity(tableName="category_templates_properties")
@PrimaryKey(name="id")
public class TemplateProperties extends BaseBean {
	
	
	
	@One2many(childClass =InfaceRules.class, parentColumn = "PropertyGuidCode",childColumn = "GuidCode" ,autoLoad=true)
	public List<InfaceRules> infaceRules ;
	
	@Many2one(forignClass =Controls.class, localColumn = "ControlGuidCode",foreignColumn = "GuidCode" ,autoLoad=true)
	public List<Controls> controls ;
	
	@Override
	public void afterLoad() throws Exception{
		//TemplateProperties t = BeanFactory.LoadBean(TemplateProperties.class);
		
		
		//List<TemplateProperties> list= BeanFactory.GetBeanList(TemplateProperties.class);
		
		if(!Utils.IsNullOrEmpty(this.getStringValue("extend_config"))){
			JSONObject jsonObj =JSONObject.fromObject(this.getStringValue("extend_config"));
			this.set("extend_config", jsonObj);			
		}
		super.afterLoad();
	}
	
	@Override
	public String generateQuerySql() {
		return "SELECT tp.id,tp.CategoryTemplateGuidCode,tp.Title,tp.Field,tp.ControlGuidCode,tp.ControlType,Sort,tp.EnableSearch,tp.GuidCode,tp.ValidateClass,tp.AsFilter,tp.FullLine,tp.DefaultValue,"
				+ " CASE WHEN ap.id IS NULL THEN 'N' ELSE 'Y' END AS InUse "
				+ " FROM category_templates_properties AS tp "
				+ " INNER JOIN category_templates AS t ON tp.CategoryTemplateGuidCode = t.GuidCode "
				+ " LEFT JOIN "
				   + " (SELECT MAX(id) AS id,property_name,CategoryCode,'Asset' AS ModuleName "
				     + " FROM asset_extend_properties WHERE property_value IS NOT NULL "
				     + " GROUP BY property_name, CategoryCode"
				     + " UNION  "
					 + " SELECT MAX(id) AS id,property_name,CategoryGuidCode AS CategoryCode,'Item' AS ModuleName"
				     + " FROM item_extend_properties WHERE property_value IS NOT NULL"
				     + " GROUP BY property_name,CategoryCode"
				+ " ) AS ap ON ap.property_name = tp.Field  AND t.ModuleName = ap.ModuleName"
				+ " AND (ap.CategoryCode = t.CategoryGuidCode)" ;
				
	}
	
}
